using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class DraggableUI : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler, IPointerDownHandler
{
    public RectTransform target;

    public void OnBeginDrag(PointerEventData eventData)
    {
    }

    public void OnDrag(PointerEventData eventData)
    {
        target.anchoredPosition += eventData.delta;
        // ClampInWindow();
    }

    public void OnEndDrag(PointerEventData eventData)
    {

    }

    void Update()
    {
        ClampInWindow();
    }

    // 限制在游戏窗口内
    private void ClampInWindow()
    {
        var x = Mathf.Clamp(target.anchoredPosition.x, -Screen.width/2 + target.rect.width/2, Screen.width/2 - target.rect.width/2);
        var y = Mathf.Clamp(target.anchoredPosition.y, -Screen.height/2 + target.rect.height/2, Screen.height/2 - target.rect.height/2);
        target.anchoredPosition = new Vector2(x, y);
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        transform.SetAsLastSibling();
    }
}
